package performance;

import org.tinygroup.logger.LogLevel;

import java.sql.*;
import java.util.Random;

/**
 * 清除TPS的测试数据
 * 
 * @author yancheng11334
 * 
 */
public class TpsUpdateData extends BaseTpsTest {

	private static String sql = "select count(1) from score";
	
	/**
	 * 清理多线程IO测试产生的测试数据
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		TpsUpdateData job = new TpsUpdateData();
		long startTime = System.currentTimeMillis();
		job.updateData();
		logger.logMessage(LogLevel.INFO, "更新数据花费时间:{}ms", System.currentTimeMillis()-startTime);
		logger.logMessage(LogLevel.INFO, "当前数据总量:{}", job.getCountNum());
	}
	
	protected static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}
	
	public int getCountNum() throws Exception{
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = getConnection();
			st = conn.createStatement();
			st.setQueryTimeout(0); 
			rs = st.executeQuery(sql);
			rs.next();
			return rs.getInt(1);
		} finally {
			close(conn);
			close(st);
			close(rs);
		}
	}
	
	public void updateData() throws Exception{
		Connection conn = null;
		PreparedStatement st = null;
		try {
			conn = getConnection();
			st = conn.prepareStatement("update score set score=?,course=? where name=?");
			st.setInt(1, 70);
			st.setString(2, "math");
			Random random = new Random();
			long id = random.nextInt(1000);
			st.setString(3, "yc"+id);
			st.setQueryTimeout(0); //时间可以设置长些，避免超时导致Query execution was interrupted 
			st.executeUpdate();
		} finally {
			close(conn);
			close(st);
		}
	}

}
